#include "mainwindow.h"
#include "./ui_mainwindow.h"

#include <QLinearGradient>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    // initPlot();
    qsrand(time(NULL));
    m_plotController = new DateTimePlotController(ui->customPlot, this);

    int graphIndex = m_plotController->addGraph("Haha");

    m_plotController->setInteractions();
    m_plotController->setTracerEnabled(true);

    QLinearGradient plotGradient;
    plotGradient.setStart(0, 0);
    plotGradient.setFinalStop(0, 350);
    plotGradient.setColorAt(0, QColor(180, 180, 180));
    plotGradient.setColorAt(1, QColor(150, 150, 150));
    m_plotController->setBackground(plotGradient);   // 设置背景颜色

    QLinearGradient axisRectGradient;
    axisRectGradient.setStart(0, 0);
    axisRectGradient.setFinalStop(0, 350);
    axisRectGradient.setColorAt(0, QColor(80, 80, 80));
    axisRectGradient.setColorAt(1, QColor(30, 30, 30));
    /* 设置QCPAxisRect背景颜色 */
    m_plotController->setAxisRectBackground(axisRectGradient);

    /* 每条网格对应一个刻度 */
    /* 网格线(对应刻度)画笔 */
    m_plotController->setGridPen(0, QPen(QColor(140, 140, 140), 1, Qt::DotLine));
    m_plotController->setGridPen(1, QPen(QColor(140, 140, 140), 1, Qt::DotLine));
    /* 子网格线(对应子刻度)画笔 */
    m_plotController->setSubGridPen(0, QPen(QColor(80, 80, 80), 1, Qt::DotLine));
    m_plotController->setSubGridPen(1, QPen(QColor(80, 80, 80), 1, Qt::DotLine));
    /* 显示子网格线 */
    m_plotController->setSubGridVisible(0, true);
    m_plotController->setSubGridVisible(1, true);

    m_plotController->setGraphName(graphIndex, "Test 1");
    m_plotController->setGraphLineStyle(graphIndex, QCPGraph::lsLine);
    m_plotController->setGraphScatterStyle(graphIndex, QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::green, Qt::red, 5)); // 设置图表散点图的样式，散点图的样式有很多种，可以自己试试

    m_plotController->setAxisRectRangeZoomFactor(1.2, 1.0);
    m_plotController->rescaleGraphAxes(0);

    m_plotController->setGraphPen(0, QPen(Qt::yellow));

    // m_plotController->s
    m_plotController->setSelectionRectPen(QPen(Qt::white));
    m_plotController->setSelectionRectBrush(QColor(0,0,100,20));
    m_plotController->setSelectionRectMode(QCP::SelectionRectMode::srmZoom);
    // m_plotController->setInteraction(QCP::iRangeDrag, false);

    // m_plotController->append(1741155842712, 1);
    // m_plotController->append(1741155843712, 2);
    m_plotController->append(QDateTime::currentDateTime(), 3);
    connect(&m_dataTimer, &QTimer::timeout, this, [=]() {
        m_plotController->append(QDateTime::currentDateTime(), qrand() % 30 - 15);
        m_plotController->rescaleGraphValueAxis(0);
        m_plotController->replot();
    });

}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_btnStartOrPause_clicked()
{
    if(m_dataTimer.isActive()) {
        m_dataTimer.stop();
        ui->btnStartOrPause->setText("Start");
    }
    else {
        m_plotController->rescaleGraphAxes(0);
        m_dataTimer.start(1000);
        ui->btnStartOrPause->setText("Pause");
    }
    // if(ui->btnStartOrPause->text() == "Start") {
    //     ui->btnStartOrPause->setText("Pause");
    //     // ui->customPlot->graph(0)->addData(m_graphKey1, m_graphData1);
    //     // ui->customPlot->graph(1)->addData(m_graphKey2, m_graphData2);
    //     for(int i = 0; i < m_graphKey1.size(); i++) {
    //         ui->customPlot->graph(0)->addData(m_graphKey1.at(i), m_graphData1.at(i));
    //         ui->customPlot->graph(1)->addData(m_graphKey1.at(i), m_graphData2.at(i));
    //     }

    //     m_graphData1.clear();
    //     m_graphData2.clear();

    // }
    // else {
    //     ui->btnStartOrPause->setText("Start");
    // }
}

void MainWindow::onRealTimeDataUpdate()
{
    static QTime startTime = QTime::currentTime();
    double key = startTime.msecsTo(QTime::currentTime())/1000.0;
    static double lastPointKey = 0;
    if (key-lastPointKey >= 0.001) // at most add point every 2 ms
    {
        // add data to lines:
        if(ui->btnStartOrPause->text() == "Start") {
            // m_graphKey1.push_back(key);
            // m_graphKey2.push_back(key);
            // m_graphData1.push_back(qSin(key)+std::rand()/(double)RAND_MAX*1*qSin(key/0.3843));
            // m_graphData2.push_back(qCos(key)+std::rand()/(double)RAND_MAX*0.5*qSin(key/0.4364));
            return;
        }
        else {
            ui->customPlot->graph(0)->addData(key, qSin(key)+std::rand()/(double)RAND_MAX*1*qSin(key/0.3843));
            ui->customPlot->graph(1)->addData(key, qCos(key)+std::rand()/(double)RAND_MAX*0.5*qSin(key/0.4364));
        }
        // rescale value (vertical) axis to fit the current data:
        ui->customPlot->graph(0)->rescaleValueAxis();
        ui->customPlot->graph(1)->rescaleValueAxis(true);
        lastPointKey = key;
    }
    else {
        return;
    }
    // make key axis range scroll with the data (at a constant range size of 8):
    ui->customPlot->xAxis->setRange(key, 8, Qt::AlignRight);
    ui->customPlot->replot();

    // calculate frames per second:
    static double lastFpsKey;
    static int frameCount;
    ++frameCount;
    if (key-lastFpsKey > 2) // average fps over 2 seconds
    {
        ui->statusbar->showMessage(
            QString("%1 FPS, Total Data points: %2")
                .arg(frameCount/(key-lastFpsKey), 0, 'f', 0)
                .arg(ui->customPlot->graph(0)->data()->size()+ui->customPlot->graph(1)->data()->size())
            , 0);
        lastFpsKey = key;
        frameCount = 0;
    }
}

void MainWindow::initPlot()
{
    QCustomPlot *customPlot = ui->customPlot;

    QCPGraph *graph = customPlot->addGraph();
    graph->setPen(QPen(QColor(40, 110, 255)));//blue
    graph = customPlot->addGraph();
    graph->setPen(QPen(QColor(255, 110, 40)));//red

    QSharedPointer<QCPAxisTickerTime> timeTicker(new QCPAxisTickerTime);
    timeTicker->setTimeFormat("%h:%m:%s.%z");
    customPlot->xAxis->setTicker(timeTicker);
    customPlot->axisRect()->setupFullAxesBox(true);
    customPlot->yAxis->setRange(-1.2, 1.2);

    //设置基本坐标轴（左侧Y轴和下方X轴）可拖动、可缩放、曲线可选、legend可选、设置伸缩比例，使所有图例可见
    customPlot->setInteractions(QCP::iRangeDrag|QCP::iRangeZoom| QCP::iSelectAxes |
                                QCP::iSelectLegend | QCP::iSelectPlottables);

    QList<QCPAxis*> axes;
    axes << customPlot->yAxis2 << customPlot->xAxis2 << customPlot->yAxis << customPlot->xAxis;
    customPlot->axisRect()->setRangeZoomAxes(axes);

    connect(&m_dataTimer, &QTimer::timeout, this, &MainWindow::onRealTimeDataUpdate);
    m_dataTimer.start(0);
}

